/**
 * Created by leo on 2/2.
 */
angular.module('panels')
    .directive('panelPortalBusinessColumns', function (tabService, loadConf, LoginInfo, Promise) {
        return {
            scope: {},
            link: function (scope) {
                var currentColumn = 0;
                loadConf('panel-portal-business-columns.yml')
                    .then(function (data) {
                        scope.columns = data;
                    });
                scope.clickService = function (service) {
                    tabService.addTab({name: service.name, url: service.url});
                };
                scope.setAsCurrent = function (index) {
                    currentColumn = index;
                };
                scope.getCurrent = function () {
                    return scope.columns ? scope.columns[currentColumn] : {};
                };
                scope.isCurrent = function (index) {
                    return currentColumn == index;
                };
                Promise.when(LoginInfo).then(function (loginInfo) {
                    // 判断当前用户是否有权限访问该service
                    scope.isAvailable = function (service) {
                        if (service._available !== undefined) {
                            return service._available;
                         }
                        var available = true,
                            enabledRoles = service.roles,
                            currentRoles = loginInfo.currentUser.roles;
                        if (angular.isArray(enabledRoles)) {
                            angular.forEach(enabledRoles, function (roleId, idx) {
                                enabledRoles[idx] = '' + roleId;
                            });
                            available = false;
                            for (var i = 0; i < currentRoles.length; i++) {
                                available = enabledRoles.indexOf(currentRoles[i].ROLE_ID) != -1;
                                if (available) break;
                            }
                        }
                        service._available = available;
                        return available;
                    };
                });
            },
            templateUrl: 'app/panel/portal/business-columns.html'
        };
    });